/*
 * @Description: ref
 * @Author: huacong
 * @Date: 2020-05-21 13:05:35
 * @LastEditTime: 2020-05-21 13:08:23
 * @LastEditors: huacong
 */
import Vue from 'vue'

const antref = Vue.directive('ant-ref', {
  bind: function bind (el, binding, vnode) {
    // 自定义指令传入值 是函数, 在这里执行 传入组件实例
    binding.value(vnode.componentInstance || el, vnode.key) // vnode.key 是使用插件时起的名称
  },
  update: function update (el, binding, vnode, oldVnode) {
    if (oldVnode.data && oldVnode.data.directives) {
      const oldBinding = oldVnode.data.directives.find(function (directive) {
        const name = directive.name
        return name === 'ant-ref'
      })
      if (oldBinding && oldBinding.value !== binding.value) {
        oldBinding && oldBinding.value(null, oldVnode.key)
        // 如果指令绑定的值有变化,则更新 组件实例
        binding.value(vnode.componentInstance || el, vnode.key)
        return
      }
    }
    // Should not have this situation
    if (vnode.componentInstance !== oldVnode.componentInstance || vnode.elm !== oldVnode.elm) {
      binding.value(vnode.componentInstance || el, vnode.key)
    }
  },
  unbind: function unbind (el, binding, vnode) {
    binding.value(null, vnode.key)
  }
})

export default antref
